<template>
	<div id="login">
		<div class="loginConbox">
			<div class="header">
			</div>
			<div class="loginBox">
				<div class="loginCon">
					<p class="title">校园点歌平台-管理后台</p>
					<p class="title">智慧校园点歌平台工作室</p>
					<el-card shadow="always" class="login-module" v-if="smdl">
						<div slot="header" class="clearfix formTitlt">
							<span>密码登录</span>
							<span class="titIconbox">
								<i class="iconfont xu-saomadenglu2 fa-lg iconcolor"></i>
								<i class="iconfont xu-saomadenglu01 el-icon--right fa-lg pointer" @click="smdl = !smdl"></i>
							</span>
						</div>
						<el-form :model="loginForm" status-icon label-width="100px" class="demo-ruleForm">
							<el-form-item>
								<el-input type="text" v-model="loginForm.username" auto-complete="off" placeholder="请输入登录账号"></el-input>
							</el-form-item>
							<el-form-item>
								<el-input type="password" v-model="loginForm.password" auto-complete="off" placeholder="请输入登录密码"></el-input>
							</el-form-item>
							<el-form-item>
								<el-button class="subBtn" type="primary" @click="submitForm">登录</el-button>
							</el-form-item>
							<p class="smalltxt">
								<a class="a" href="http://www.jgsusa.top/">工作室官网</a>
								<a class="a" href="https://www.cnblogs.com/xgp123/">站长博客</a>
								<a class="a" href="http://sighttp.qq.com/authd?IDKEY=cfa0c276205f744a7064b3c39b0c36228ce416f405339cee">联系站长</a>
							</p>
						</el-form>
					</el-card>

					<el-card shadow="always" class="login-module" v-else>
						<div slot="header" class="clearfix formTitlt">
							<span>扫码登陆</span>
							<span class="titIconbox">
								<i class="iconfont xu-mimadenglu1 fa-lg iconcolor"></i>
								<i class="iconfont xu-imagevector el-icon--right fa-lg pointer" @click="smdl = !smdl"></i>
							</span>
						</div>
						<div class="ewmbox">
							<div class="ewm">
								<img src="../../assets/qq.jpg">
							</div>
							<div class="ewmicon">
								<i class="iconfont xu-saomadenglu fa-2x iconcolor"></i>
								<p>该功能尚未绑定，敬请期待</p>
							</div>
							<p class="smalltxt">
								<a class="a" href="http://www.jgsusa.top/">工作室官网</a>
								<a class="a" href="https://www.cnblogs.com/xgp123/">站长博客</a>
								<a class="a" href="http://sighttp.qq.com/authd?IDKEY=cfa0c276205f744a7064b3c39b0c36228ce416f405339cee">联系站长</a>
							</p>
						</div>
					</el-card>

					<el-dialog title="人脸识别登陆 —— 请正对摄像头!" :visible.sync="dialogVisible" :before-close="handleClose" width="60%" top="20px">
						<!-- <div class="demo-frame"> -->
							<div class="demo-container">
								<video id="video" width="320" height="240" preload autoplay loop muted></video>
								<canvas id="canvas" width="320" height="240"></canvas>
							</div>
						<!-- </div> -->
					</el-dialog>
				</div>
			</div>
		</div>
	</div>

</template>
<script>
	import './tracking-min.js'
	import './face-min.js'
	// import './stats.min.js'

	export default {
		data() {
			return {
				smdl: true,
				loginForm: {
					username: '',
					password: ''
				},
				dialogVisible: false
			}
		},
		created() {
			this.axios.get(this.server + '/account/isFlaceIp').then(res => {
				if (res.data == '1') {
					//弹出人脸识别的对话框来
					this.dialogVisible = true;
				}
			}, res => {

			})
		},
		// mounted() {
		// 	   // this.getCompetence()
		// },
		updated() {
			if (this.dialogVisible) {
				// 		// alert("xxx")
				var video = this.mediaStreamTrack = document.getElementById('video');
				var canvas = document.getElementById('canvas');
				var context = canvas.getContext('2d');

				let tracker = new window.tracking.ObjectTracker('face');
				tracker.setInitialScale(4);
				tracker.setStepSize(2);
				tracker.setEdgesDensity(0.1);

				this.trackerTask = window.tracking.track('#video', tracker, {
					camera: true
				});

				let flag = true;
				var that = this;
				var count = 0;
				tracker.on('track', function(event) {
					context.clearRect(0, 0, canvas.width, canvas.height);
					event.data.forEach(function(rect) {
						context.strokeStyle = '#a64ceb';
						context.strokeRect(rect.x, rect.y, rect.width, rect.height);
						context.font = '11px Helvetica';
						context.fillStyle = "#fff";
						context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
						context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
					});
					if (event.data.length) {
						// 会不停的去检测人脸，所以这里需要做个锁
						if (flag) {
							// console.log(flag)
							// 裁剪出人脸并绘制下来
							const canvasUpload = document.getElementById('canvas')
							const contextUpload = canvasUpload.getContext('2d')
							contextUpload.drawImage(video, 0, 0, 105, 105)
							flag = false
							// 人脸的basa64
							const dataURL = canvasUpload.toDataURL('image/jpeg');
							// console.log(dataURL.slice(23))
							that.$message.info("检测到人脸，正在验证！")
							
							// const params =  new FormData()
							// params.append('img',  dataURL.slice(23))
														
							// 发送axios请求
							that.axios.post(that.server + '/account/faceLogin', dataURL.slice(23)).then(res => {
								if(res.data != '0') {
									// 登陆成功
									that.$message.success("人脸登陆成功！")
									that.mediaStreamTrack.srcObject.getTracks()[0].stop();
									that.trackerTask.stop()
									that.dialogVisible = false;
									// 成功回调
									// 将 username 设置为 token 存储在 store，仅为测试效果，实际存储 token 以后台返回为准
									that.$store.dispatch('setToken', res.data).then(() => {
										that.$router.push({
											path: '/'
										})
									}).catch(res => {
										that.$message({
											showClose: true,
											message: res,
											type: 'error'
										})
									})
								}else {
									that.$message.error("人脸登陆失败，正在重试！")
									count++;
									if(count >= 3) {
										clearTimeout(that.timer);  //清除延迟执行
										 
										that.timer = setTimeout(()=>{   //设置延迟执行
											_this.$router.go(0)
										},1000);
										
										that.$message.error("查无此人，请手动登陆！")
										that.mediaStreamTrack.srcObject.getTracks()[0].stop();
										that.trackerTask.stop()
										that.dialogVisible = false;
									}else {
										flag = true
									}
								}
							},res => {
								that.$message.error("网络错误，请检查网络！")
								that.mediaStreamTrack.srcObject.getTracks()[0].stop();
								that.trackerTask.stop()
								that.dialogVisible = false;
							})
							// // ajax请求
							// that.$store.dispatch('LoginByFaceID', {
							// 	face_img: dataURL.slice(23) // 我们后台需要的basa64不要前缀
							// }).then(res => {
							// 	let type = 'success'
							// 	// 登录成功跳转到首页
							// 	if (res.data.code === 200) {
							// 		_this.$router.push({
							// 			path: '/'
							// 		});
							// 	}
							// 	// 登录失败重新进行人脸检测
							// 	else {
							// 		type = 'error'
							// 		setTimeout(() => {
							// 			flag = true
							// 		}, 1500)
							// 	}
							// 	_this.$message({
							// 		message: res.data.message,
							// 		type,
							// 		center: true
							// 	});
							// }).catch(error => {
							// 	console.log(error)
							// })
						}
					}
				});
			}
		},
		methods: {

			handleClose(done) {
				this.$confirm('你确定不进行人脸识别登陆吗？')
					.then(_ => {
						if (this.mediaStreamTrack) {
							this.mediaStreamTrack.srcObject.getTracks()[0].stop();
							this.trackerTask.stop()
						}

						this.dialogVisible = false;
						done();
					})
					.catch(_ => {});
			},
			submitForm() {
				let that = this
				if (this.loginForm.username === '' || this.loginForm.password === '') {
					this.$message({
						showClose: true,
						message: '账号或密码不能为空',
						type: 'error'
					})
					return false
				} else {
					this.axios.get(this.server + "/account/login" +
						"?username=" + this.loginForm.username + "&password=" + this.loginForm.password
					).then(res => {
						if (res.data == 0) {
							this.$message({
								showClose: true,
								message: '登陆失败',
								type: 'error'
							})
							return false;
						}
						// 成功回调
						// 将 username 设置为 token 存储在 store，仅为测试效果，实际存储 token 以后台返回为准
						that.$store.dispatch('setToken', res.data).then(() => {
							that.$router.push({
								path: '/'
							})
						}).catch(res => {
							that.$message({
								showClose: true,
								message: res,
								type: 'error'
							})
						})
					}, res => {
						// 错误回调
						that.$message({
							showClose: true,
							message: "请求失败",
							type: 'error'
						})
					})
				}
			},
			message() {
				const h = this.$createElement;
				this.$notify({
					title: '温馨提示',
					message: h('i', {
						style: 'color: teal'
					}, '请认真填写本平台分配的账号，如需加盟，请联系qq: 2043928998，谢谢！'),
					duration: 6000
				});
			},
		},
		mounted() {
			this.message()
		}
	}
</script>
<style lang="scss">
	@import "./demo.css";
	#login {
		width: 100%;
		height: 100%;
		background-color: #2d3a4b;

		.loginConbox {
			background: #2d3a4b;
		}

		.header {
			height: 60px;
			position: relative;
			background: #2d3a4b;

			/*border-bottom: 1px solid rgba(255, 255, 255, 0.3);*/
			.logo {
				margin-left: 30px;
				width: 500px;
				float: left;
				height: 40px;
				padding-top: 10px;

				img {
					height: 100%;
				}
			}
		}

		.loginBox {
			.iconcolor {
				color: #409EFF;
			}

			padding: 74px 0 118px;

			.loginCon {
				width: 990px;
				margin: auto;
				position: relative;
				height: 388px;

				.el-card__header {
					border-bottom: 0px;
				}

				.title {
					font-size: 36px;
					font-weight: 600;
					color: #ffffff;
					width: 500px;
					float: left;
					margin-top: 0px;

					&:first-child {
						font-size: 34px;
						margin-top: 50px;
						margin-bottom: 30px;
					}
				}

				.login-module {
					width: 380px;
					height: 325px;
					margin-top: 60px;
					border: none;
					position: absolute;
					right: 0;

					.formTitlt {
						font-size: 18px;
						font-weight: 400;

						.titIconbox {
							float: right;

							.pointer {
								cursor: pointer;
							}
						}
					}

					.smalltxt {
						text-align: right;

						.a {
							text-decoration: none;
							color: #999999;
							font-size: 12px;
							margin-left: 8px;
						}
					}
				}

				.el-form-item__content {
					margin-left: 0px !important;

					.subBtn {
						width: 100%;
					}
				}
			}

			.el-input__inner,
			.el-button,
			.el-card,
			.el-message {
				border-radius: 0px !important;
			}

			.el-form-item__content .ico {
				position: absolute;
				top: 0px;
				left: 0px;
				z-index: 999;
				width: 40px;
				height: 39px;
				text-align: center;
				border-right: 1px solid #ccc;
			}

			.ewmbox {
				width: 100%;
				height: 240px;
				margin-top: -25px;

				.ewm {
					width: 140px;
					height: 140px;
					margin: 20px auto;

					p {
						font-size: 12px;
						padding-left: 40px;
						margin: 0;
					}
				}

				.ewmicon {
					width: 140px;
					margin: 20px auto 0;

					.iconfont {
						float: left;
					}

					p {
						font-size: 12px;
						padding-left: 40px;
						margin: 0;
					}
				}
			}
		}
	}
</style>
